package com.mic.netty.server;

import com.mic.netty.MessageType;
import com.mic.netty.pojo.Header;
import com.mic.netty.pojo.NettyMessage;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author yangjiaqi
 */
public class HeartBeatRespHandler extends ChannelHandlerAdapter{

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessage nettyMessage = (NettyMessage) msg;
        if (nettyMessage.getHeader() != null && nettyMessage.getHeader().getType() == MessageType.HEARTBEAT_REQ.value()) {
            System.out.println("Receive client heart beat message : ---> " + nettyMessage);
            NettyMessage message = buildHeatBeat();
            System.out.println("send heart beat response message to client : --->" + message);
            ctx.writeAndFlush(message);
        }else {
            ctx.fireChannelRead(msg);
        }
    }
    private NettyMessage buildHeatBeat() {
        NettyMessage nettyMessage = new NettyMessage();
        Header header = new Header();
        header.setType(MessageType.HEARTBEAT_RESP.value());
        nettyMessage.setHeader(header);
        return nettyMessage;
    }
}
